package com.auto.survey.activity.monitoring.station

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.adapter.CtrlPointAdapter
import com.auto.survey.activity.monitoring.adapter.CtrlPointAdapter.OnItemClickListener
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.Point
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_BASE_POINT_LIST
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_CHOICKE_POINT_REASULT_OK
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_CTRL_POINT_LIST
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.Command
import com.auto.survey.util.Helper
import com.auto.survey.util.Helper.formatTimestamp
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import kotlinx.coroutines.launch

/**
 * 控制基点列表，用于创建时候从数据库导入
 */
class CreateStationForCtrlPActivity :BaseActivity(){

    private var projectId:Int = -1
    private var objectId:Int = -1
    private val database = MonitoringRepository()
    private var mChoiceItems =  mutableListOf<MonitoringPoint>()
    private val mContainsItems : MutableMap<Int, MonitoringPoint> = mutableMapOf()
    // 缓存容器：存储被移除的对象（集合B中已删除的id对应的对象）
    private val cachedMap: MutableMap<Int, MonitoringPoint> = mutableMapOf()


    override fun initView() {
        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)

        val points = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableArrayListExtra(CREATE_STATION_CTRL_POINT_LIST, MonitoringPoint::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableArrayListExtra(CREATE_STATION_CTRL_POINT_LIST)
        }

        Log.i("CreateStActivity", "points size = ${points?.size}")

        if (points != null) {
            mChoiceItems = points

            points.forEach {
                cachedMap[it.id] = it
                mContainsItems[it.id] = it
            }
        }

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("基点列表")
        mComment_title?.setRightTitle("保存")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{
            val intent = Intent()
            val data = ArrayList(mChoiceItems)
            Log.i("CreateStActivity", "itent data size = ${data.size}")
            intent.putParcelableArrayListExtra(CREATE_STATION_BASE_POINT_LIST, data)
            setResult(CREATE_STATION_CHOICKE_POINT_REASULT_OK, intent)
            finish()
        })

        val rv_cs_ctrlp = findViewById<RecyclerView>(R.id.rv_cs_ctrlp)
        rv_cs_ctrlp.layoutManager = LinearLayoutManager(this)
        val checkedPoints: ArrayList<Point> = ArrayList()
        points?.forEach {
            val checkedp = Point(id = it.id, monitoringObjectId= it.monitoringObjectId,
                pointName =it.pointName,
                pointX=it.pointX,
                pointY = it.pointY,
                pointZ = it.pointZ,
                pointType=it.pointType)
            checkedPoints.add(checkedp)
        }

        val adapter = CtrlPointAdapter(checkedPoints)
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(items: List<Point>) {

                // 找出 id 相同的元素
                items.forEach {
                   if (!mContainsItems.containsKey(it.id)) {
                       // 先查缓存，有则复用（移回当前容器），无则新建
                       val cached = cachedMap.remove(it.id)
                       mContainsItems[it.id] = cached?:MonitoringPoint(id = it.id, monitoringObjectId= it.monitoringObjectId, stationId = -1,
                           pointName = it.pointName, pointCode = "", pointX = it.pointX, pointY = it.pointY, pointZ = it.pointZ,
                           collected = true, pointHz = null, pointV = null, pointSD = null, mirrorHeight = 0.0,
                           pointType = it.pointType, isWarning=false,mirrorType = 0,
                           createTime= formatTimestamp(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"),
                           updateTime="")
                   }

                }

                // 2. 处理删除：集合B没有但当前A有的id（移到缓存容器）
                val idsInB = items.map { it.id }.toSet()
                val idsToRemove = mContainsItems.keys - idsInB // 求差集：当前A有但B没有的id



                idsToRemove.forEach {id->
                    // 从当前容器移到缓存容器（而非删除）
                    mContainsItems.remove(id)?.let { cachedMap[id] = it }
                }

                mChoiceItems.clear()
                mChoiceItems.addAll(mContainsItems.values)

                Log.i("CreateStActivity", "items size = ${items.size}")
            }

        })
        rv_cs_ctrlp.adapter = adapter


        lifecycleScope.launch {
            database.getPointByObjectIdAndPtype(objectId, Command.pointTypaList()[1]).collect{
                adapter.setItems(it)
            }
        }

    }


    override fun getLayoutId(): Int {

        return R.layout.activity_create_station_ctrlp
    }

}